package cn.datawin.task.dao;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import org.apache.commons.lang.math.RandomUtils;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;

public class DbUtil {

	public static DB db;

	public static void connect() throws IOException {
		db = new DataSource().getDB();
	}

	public static DBCollection getcoll(String coll) {
		return db.getCollection(coll);
	}

	public static String saveImg(String coll, byte[] data, String fileName) {
		GridFS gfsPhoto = new GridFS(db, coll);
		GridFSInputFile gfsFile = gfsPhoto.createFile(data);
		gfsFile.setFilename(fileName);
		String id = UUID.randomUUID().toString();
		gfsFile.setId(id);
		gfsFile.save();
		return id;
	}

	public static InputStream getImg(String coll, String id) {
		GridFS gridFS = new GridFS(db, coll);
		GridFSDBFile dbfile = gridFS.findOne(new BasicDBObject("_id", id));
		return dbfile.getInputStream();
	}
	
	public static void main(String[] args) throws IOException {
		connect();
		File file = new File("D:/wqe/psb.jpg");
		ByteArrayOutputStream  out = new  ByteArrayOutputStream();
//		FileUtils.copyFile(file, out);
		String id = saveImg("img", out.toByteArray(), "aa.jpg");
		System.out.println(id);
		InputStream in = getImg("img", id);
//		FileUtils.copyInputStreamToFile(in, new File("d://aa.jpg"));
	}

}
